﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SysInfo;
using CubeDAL;

namespace CrossQuery
{
    public class ComboType : IType
    {
        private List<ComboNode> combo_list;
        private string selected_value;

        public ComboType(string source_sql)
        {
            combo_list = new List<ComboNode>();
            Initial(source_sql);
            if (combo_list.Count() > 0)
                selected_value = combo_list[0].Code;
            else
                selected_value = "-1";
        }

        public string Type 
        {
            get { return "Combo"; }
        }

        /// <summary>
        /// Return ComboNode according to given index
        /// </summary>
        /// <param name="index">Index</param>
        /// <returns>a combo node</returns>
        public ComboNode this[int index]
        {
            get { return combo_list[index]; }
        }

        public int Count
        {
            get { return combo_list.Count; }
        }

        /// <summary>
        /// Value is the code of certain combo-item
        /// </summary>
        public string Value 
        {
            get
            {
                return selected_value;
            }
            set
            {
                foreach (var node in combo_list)
                {
                    if (node.Code == value)
                    {
                        selected_value = value;
                        return;
                    }
                }
                selected_value = "-1";
            }
        }
        public string ToSQLString()
        {
            return "'" + selected_value + "'";
        }

        private void Initial(string sql)
        {
            string user = Constant.DB_USER;
            string pwd = Constant.DB_PASSWORD;
            string server = Constant.DB_SERVER;
            string database = Constant.DB_MAP_DATABASE;
            string[] o_fields = { "code", "item" };

            MySQLWrapper wrapper = new MySQLWrapper(server, database, user, pwd);
            List<List<string>> res = wrapper.Select(sql, o_fields);
            foreach (var tuple in res)
            { 
                combo_list.Add(new ComboNode(tuple[0], tuple[1]));
            }
        }
    }

    public class ComboNode
    {
        private KeyValuePair<string, string> data;

        public ComboNode(string code, string display_name)
        {
            data = new KeyValuePair<string, string>(code, display_name);
        }

        public string DisplayName
        {
            get { return data.Value; }
        }

        public string Code
        {
            get { return data.Key; }
        }

        public override string ToString()
        {
            return this.DisplayName;
        }
    }
}
